/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.security.provider;

import java.util.LinkedList;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

import org.beaconframework.ext.rs.WebResource;
import org.beaconframework.ext.rs.WebResourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;

public class BasicAuthProxyProvider extends
        AbstractUserDetailsAuthenticationProvider implements
        ApplicationContextAware {

    private ApplicationContext applicationContext;

    private Logger log = LoggerFactory.getLogger(BasicAuthProxyProvider.class);

    private WebResourceFactory webResourceFactory;


    @Override
    protected void additionalAuthenticationChecks(UserDetails arg0,
            UsernamePasswordAuthenticationToken arg1)
            throws AuthenticationException {

    }


    public BasicAuthProxyProvider() {
        super();

    }


    public WebResourceFactory getWebResourceFactory() {

        return webResourceFactory;

    }


    public WebResource createAuthCheckWebResource() {
        return getWebResourceFactory().createWebResource();
    }


    @Override
    protected UserDetails retrieveUser(String arg0,
            UsernamePasswordAuthenticationToken arg1)
            throws AuthenticationException {
        log.debug("authenticating: {}", arg1.getName());
        WebResource wr = createAuthCheckWebResource();

        try {
            Response s = wr.get(Response.class);

            if (s.getStatus() == 200) {

                User sud = new User(arg1.getName(), "" + arg1.getCredentials(),
                        true, true, true, true,
                        new LinkedList<GrantedAuthority>());

                return sud;
            }

            throw new BadCredentialsException("Status code: " + s.getStatus());

        } catch (WebApplicationException e) {
            if (e.getResponse().getStatus() == 401) {

                throw new BadCredentialsException("Invalid login: " + arg0);
            }
        } catch (RuntimeException e) {
            throw new AuthenticationServiceException("Caught RuntimeException "
                    + e, e);
        }

        throw new AuthenticationServiceException("");

    }


    public void setWebResourceFactory(WebResourceFactory webResourceFactory) {
        this.webResourceFactory = webResourceFactory;
    }


    @Override
    public boolean supports(Class<? extends Object> arg0) {
        if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(arg0)) {

            return true;
        }

        return false;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;

    }


    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

}
